package com.example.translateappjava.Service.AliyunAPI;

import android.app.Activity;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class AliyunAPIHelper {
    private final Activity activity;
    private AliyunAPIHelper.AliyunAPIListener listener;
    public AliyunAPIHelper(Activity activity) {
        this.activity = activity;
    }

    public interface AliyunAPIListener {
        void AliyunAPIResponse(String response, int index);
        void AliyunAPIError(String message);
    }
    public void setAliyunAPIListener(AliyunAPIListener listener) {
        this.listener = listener;
    }
    /**
     * @param filePath 请求照片的本地地址
     * */
    public void AliyunAPIFilePathRequest(byte[] filePath, int index){
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 在后台线程中执行网络请求
                String response = "没调用到";
                String name = "没调用到";
                try {
                    response = performFilePathNetworkRequest(filePath);
//                    Log.v("response:", response);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("出错了"+e);
                }

                // 在 UI 线程中处理网络请求结果
                try {
                    // 将响应字符串转换为 JSONObject
                    JSONObject jsonObject = new JSONObject(response);

                    // 获取 "result" 数组
                    JSONArray resultArray = jsonObject.getJSONArray("result");

                    // 获取第一个元素
                    JSONObject firstResult = resultArray.getJSONObject(0);

                    // 从第一个元素获取 "name"
                     name = firstResult.getString("name");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String finalResponse = name;
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 在这里更新 UI
                        if (listener != null) {
                            listener.AliyunAPIResponse(finalResponse, index);
                        }
                    }
                });
            }
        }).start();
    }


    private String performFilePathNetworkRequest(byte[] filePath) throws Exception {
        AliyunAPIImplication aliyunAPIImplication = new AliyunAPIImplication();
        return aliyunAPIImplication.getFilePathRecognizeResult(filePath);
    }
}
